package com.osgix.common.utils.xmlUtil.test;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlValue;

public class JAXB2Tester {

	public static void main(String[] args) throws JAXBException, IOException {
		/*
		//下面代码演示将上面生成的xml转换为对象
		/*
		FileReader fr = new FileReader("person.xml");
		Unmarshaller um = context.createUnmarshaller();
		Person p2 = (Person)um.unmarshal(fr);
		System.out.println("Country:"+p2.getAddress().getCountry());
		*/

		Item item6 = new Item();
		item6.setId("6");
		item6.setText("item6");

		Item item7 = new Item();
		item7.setId("7");
		item7.setText("item7");

		List<Item> items3 = new ArrayList<Item>();
		items3.add(item6);
		items3.add(item7);

		Item item4 = new Item();
		item4.setId("4");
		item4.setText("item4");

		Item item5 = new Item();
		item5.setId("5");
		item5.setText("item5");

		List<Item> items2 = new ArrayList<Item>();
		items2.add(item4);
		items2.add(item5);

		Item item2 = new Item();
		item2.setId("2");
		item2.setText("item2");
		item2.setItem(items2);//

		Item item3 = new Item();
		item3.setId("3");
		item3.setText("item3");
		item3.setItem(items3);//

		List<Item> items1 = new ArrayList<Item>();
		items1.add(item2);
		items1.add(item3);

		Item item1 = new Item();
		item1.setId("1");
		item1.setText("item1");
		item1.setItem(items1);//

		JAXBContext context = JAXBContext.newInstance(item1.getClass());
		Marshaller m = context.createMarshaller();
		m.setProperty("jaxb.encoding", "utf-8");
		m.setProperty("jaxb.formatted.output", true);
		StringWriter sw = new StringWriter();
		m.marshal(item1, sw);
		System.out.println(sw.getBuffer().toString());
	}
}

class SubBean {
}

class Bean {
	@XmlElements({ @XmlElement(name = "a", type = BeanA.class), @XmlElement(name = "b", type = BeanB.class) })
	private List<SubBean> data = new ArrayList<SubBean>();
}

class BeanA extends SubBean {

	@XmlValue
	private String data;
}

class BeanB extends SubBean {

	@XmlValue
	private String data;
}
